import json

class FriendSet:
    def __init__(self):
        """初始化好友管理系统，加载已保存的数据"""
        self.friend_list = []  # 存储所有好友信息
        self.groups = {}  # 存储分组信息，格式: {分组名: [好友1, 好友2]}
        self.load_data()

    def load_data(self):
        """从文件加载数据"""
        try:
            with open('friends_data.json', 'r', encoding='utf-8') as f:
                data = json.load(f)
                self.friend_list = data.get('friend_list', [])
                self.groups = data.get('groups', {})
        except (FileNotFoundError, json.JSONDecodeError):
            self.friend_list = []
            self.groups = {}

    def save_data(self):
        """将数据保存到文件"""
        try:
            with open('friends_data.json', 'w', encoding='utf-8') as f:
                json.dump({
                    'friend_list': self.friend_list,
                    'groups': self.groups
                }, f, ensure_ascii=False, indent=2)
        except Exception as e:
            print(f"保存数据失败: {e}")

    def add_friend(self):
        """添加新好友"""
        name = input("请输入好友姓名: ").strip()
        if not name:
            print("姓名不能为空!")
            return

        # 检查好友是否已存在
        if name in self.friend_list:
            print(f"好友 '{name}' 已存在!")
            return

        phone = input("请输入好友电话号码(可选，直接回车跳过): ").strip()
        email = input("请输入好友邮箱(可选，直接回车跳过): ").strip()

        friend_info = {'name': name}
        if phone:
            friend_info['phone'] = phone
        if email:
            friend_info['email'] = email

        self.friend_list.append(friend_info)
        print(f"好友 '{name}' 添加成功!")

        # 添加到分组
        add_to_group = input("是否添加到分组? (y/n): ").lower()
        if add_to_group == 'y':
            self._add_friend_to_group(name)

        self.save_data()

    def _add_friend_to_group(self, friend_name):
        """将好友添加到分组(内部使用)"""
        group_name = input("请输入分组名称: ").strip()
        if not group_name:
            print("分组名称不能为空!")
            return

        # 如果分组不存在，创建新分组
        if group_name not in self.groups:
            self.groups[group_name] = []

        # 添加好友到分组
        if friend_name not in [f['name'] for f in self.groups[group_name]]:
            # 查找好友完整信息
            friend_info = next((f for f in self.friend_list if f['name'] == friend_name), None)
            if friend_info:
                self.groups[group_name].append(friend_info)
                print(f"好友 '{friend_name}' 已添加到分组 '{group_name}'")
                self.save_data()
            else:
                print(f"未找到好友 '{friend_name}'")
        else:
            print(f"好友 '{friend_name}' 已在分组 '{group_name}' 中")

    def modify_friend(self):
        """修改好友信息"""
        name = input("请输入要修改的好友姓名: ").strip()
        if not name:
            print("姓名不能为空!")
            return

        # 查找好友
        friend_info = next((f for f in self.friend_list if f['name'] == name), None)
        if not friend_info:
            print(f"未找到好友 '{name}'")
            return

        print(f"当前好友信息: {friend_info}")
        new_name = input(f"请输入新姓名(保持不变直接回车，当前: {friend_info['name']}): ").strip()
        new_phone = input(f"请输入新电话号码(保持不变直接回车，当前: {friend_info.get('phone', '')}): ").strip()
        new_email = input(f"请输入新邮箱(保持不变直接回车，当前: {friend_info.get('email', '')}): ").strip()

        # 更新信息
        if new_name:
            old_name = friend_info['name']
            friend_info['name'] = new_name

            # 更新分组中的好友名称
            for group in self.groups.values():
                for idx, friend in enumerate(group):
                    if friend['name'] == old_name:
                        group[idx]['name'] = new_name

        if new_phone:
            friend_info['phone'] = new_phone
        if new_email:
            friend_info['email'] = new_email

        print(f"好友信息更新成功: {friend_info}")
        self.save_data()

    def delete_friend(self):
        """删除好友"""
        name = input("请输入要删除的好友姓名: ").strip()
        if not name:
            print("姓名不能为空!")
            return

        # 查找好友
        friend_info = next((f for f in self.friend_list if f['name'] == name), None)
        if not friend_info:
            print(f"未找到好友 '{name}'")
            return

        # 确认删除
        confirm = input(f"确定要删除好友 '{name}' 吗? (y/n): ").lower()
        if confirm != 'y':
            print("已取消删除")
            return

        # 从好友列表删除
        self.friend_list = [f for f in self.friend_list if f['name'] != name]

        # 从所有分组删除
        for group in self.groups.values():
            group[:] = [f for f in group if f['name'] != name]

        print(f"好友 '{name}' 已删除")
        self.save_data()

    def show_friend(self):
        """展示好友信息"""
        print("\n1. 展示所有好友")
        print("2. 按分组展示好友")
        print("3. 展示所有分组")
        option = input("请选择操作(1-3): ").strip()

        if option == '1':
            self._show_all_friends()
        elif option == '2':
            self._show_friends_by_group()
        elif option == '3':
            self._show_all_groups()
        else:
            print("无效的选项")

    def _show_all_friends(self):
        """展示所有好友"""
        if not self.friend_list:
            print("当前没有任何好友")
            return

        print("\n所有好友:")
        for idx, friend in enumerate(self.friend_list, 1):
            print(f"{idx}. {friend['name']}")
            if 'phone' in friend:
                print(f"   电话: {friend['phone']}")
            if 'email' in friend:
                print(f"   邮箱: {friend['email']}")
            print("-" * 20)

    def _show_friends_by_group(self):
        """按分组展示好友"""
        if not self.groups:
            print("当前没有任何分组")
            return

        print("\n可用分组:")
        for idx, group_name in enumerate(self.groups.keys(), 1):
            print(f"{idx}. {group_name} ({len(self.groups[group_name])} 个好友)")

        group_idx = input("请选择要查看的分组序号(输入0返回): ").strip()
        if not group_idx.isdigit():
            print("无效的序号")
            return

        group_idx = int(group_idx)
        if group_idx == 0:
            return

        groups_list = list(self.groups.keys())
        if 1 <= group_idx <= len(groups_list):
            group_name = groups_list[group_idx - 1]
            friends_in_group = self.groups[group_name]

            print(f"\n分组 '{group_name}' 中的好友:")
            for idx, friend in enumerate(friends_in_group, 1):
                print(f"{idx}. {friend['name']}")
                if 'phone' in friend:
                    print(f"   电话: {friend['phone']}")
                if 'email' in friend:
                    print(f"   邮箱: {friend['email']}")
                print("-" * 20)
        else:
            print("无效的序号")

    def _show_all_groups(self):
        """展示所有分组"""
        if not self.groups:
            print("当前没有任何分组")
            return

        print("\n所有分组:")
        for idx, (group_name, friends) in enumerate(self.groups.items(), 1):
            print(f"{idx}. {group_name} ({len(friends)} 个好友)")

    def create_group(self):
        """创建新分组"""
        group_name = input("请输入新分组名称: ").strip()
        if not group_name:
            print("分组名称不能为空!")
            return

        if group_name in self.groups:
            print(f"分组 '{group_name}' 已存在!")
            return

        self.groups[group_name] = []
        print(f"分组 '{group_name}' 创建成功!")

        # 添加好友到分组
        add_friends = input("是否现在添加好友到该分组? (y/n): ").lower()
        if add_friends == 'y':
            while True:
                friend_name = input("请输入要添加的好友姓名(直接回车结束): ").strip()
                if not friend_name:
                    break

                friend_info = next((f for f in self.friend_list if f['name'] == friend_name), None)
                if friend_info:
                    if friend_info not in self.groups[group_name]:
                        self.groups[group_name].append(friend_info)
                        print(f"好友 '{friend_name}' 已添加到分组 '{group_name}'")
                    else:
                        print(f"好友 '{friend_name}' 已在分组 '{group_name}' 中")
                else:
                    print(f"未找到好友 '{friend_name}'")

            self.save_data()

    def delete_group(self):
        """删除分组"""
        if not self.groups:
            print("当前没有任何分组")
            return

        print("\n可用分组:")
        for idx, group_name in enumerate(self.groups.keys(), 1):
            print(f"{idx}. {group_name} ({len(self.groups[group_name])} 个好友)")

        group_idx = input("请选择要删除的分组序号(输入0返回): ").strip()
        if not group_idx.isdigit():
            print("无效的序号")
            return

        group_idx = int(group_idx)
        if group_idx == 0:
            return

        groups_list = list(self.groups.keys())
        if 1 <= group_idx <= len(groups_list):
            group_name = groups_list[group_idx - 1]

            # 确认删除
            confirm = input(f"确定要删除分组 '{group_name}' 吗? (y/n): ").lower()
            if confirm == 'y':
                del self.groups[group_name]
                print(f"分组 '{group_name}' 已删除")
                self.save_data()
        else:
            print("无效的序号")

def main():
    """主程序入口"""
    print("=" * 30)
    print("欢迎使用好友管理系统")
    print("=" * 30)

    friend_set = FriendSet()

    while True:
        print("\n请选择操作:")
        print("1. 添加好友")
        print("2. 修改好友信息")
        print("3. 删除好友")
        print("4. 展示好友信息")
        print("5. 创建分组")
        print("6. 删除分组")
        print("0. 退出系统")

        choice = input("请输入选项(0-6): ").strip()

        if choice == '1':
            friend_set.add_friend()
        elif choice == '2':
            friend_set.modify_friend()
        elif choice == '3':
            friend_set.delete_friend()
        elif choice == '4':
            friend_set.show_friend()
        elif choice == '5':
            friend_set.create_group()
        elif choice == '6':
            friend_set.delete_group()
        elif choice == '0':
            print("感谢使用好友管理系统，再见!")
            break
        else:
            print("无效的选项，请重新输入")

if __name__ == "__main__":
    main()